<template>
  <div id="map" style="height: 300px;width: 100%"></div>
</template>

<script>
  var geocoder, map, marker = null, markersArray = [];
  export default {
    props: {
      lat: Number,
      lng: Number
    },
    mounted() {
      // this.init()
    },
    methods: {
      init(lat, lnt) {
        this.setCenter(lat, lnt)
        //地址和经纬度之间进行转换服务
        geocoder = new qq.maps.Geocoder();
        //设置服务请求成功的回调函数

//         geocoder.setComplete(function(result) {
//           map.setCenter(result.detail.location);
//           let position = {
//             lat:35.792945,
//             lug:112.928676
//           }
//           console.log('jjjjjjjjjj::')
//           marker = new qq.maps.Marker({
//             map: map,
//             position: position
//           })
//           console.log('ssss')
// //          this.addMarker(result.detail.location)
//         });

        var _this = this
        qq.maps.event.addListener(
          map,
          'click',
          function (event) {
            _this.delMarker()
            _this.addMarker(event.latLng)
            // _this.setCenter(Number(event.latLng.getLat()), Number(event.latLng.getLng()))
            let location = {
              lng: event.latLng.getLng(),
              lat: event.latLng.getLat()
            }
            _this.$emit('location', location)
          }
        );

        //若服务请求失败，则运行以下函数
        geocoder.setError(function () {
          alert("出错了，请输入正确的地址！！！");
        });
      },
      setCenter(lat, lnt) {
        var center = new qq.maps.LatLng(lat, lnt);
        map = new qq.maps.Map(document.getElementById('map'), {
          center: center,
          zoom: 18,
        });
        var marker = new qq.maps.Marker({
          position: center,
          map: map
        });

        let location = {
          lng: lnt,
          lat: lat
        }
        this.$emit('location', location)

        markersArray.push(marker)

      },
      addMarker(mark) {
        var marker = new qq.maps.Marker({
          map: map,
          position: mark
        });
        markersArray.push(marker)
      },
      delMarker() {
        if (markersArray) {
          for (let i = 0; i < markersArray.length; i++) {
            markersArray[i].setMap(null);
          }
        }
      }
    }
  }
</script>
